package com.example.file_management.service;

import com.example.file_management.mapper.user.AuthMapper;
import com.example.file_management.pojo.user.Auth;
import com.example.file_management.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.example.file_management.pojo.user.Role;
import com.example.file_management.mapper.user.GroupMapper;
import com.example.file_management.pojo.user.Group;

import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class AuthService {

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private RoleService roleService; // 角色校验
    @Autowired
    private GroupMapper groupMapper; // 注入 GroupMapper
    @Autowired
    private JwtUtil jwtUtil;

    private static final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public Auth getUserByUsername(String username) {
        return authMapper.findByUsername(username);
    }

    // 用户登录
    public String login(String username, String password) {
        Auth user = authMapper.findByUsername(username);

        if (user == null) {
            throw new IllegalArgumentException("用户名不存在");
        }

        // 验证密码（如果数据库存储的是加密密码，需要使用 passwordEncoder.matches）
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }

        // 生成 JWT 令牌
        return jwtUtil.generateToken(user);
    }

    // 获取所有用户
    public List<Auth> getAllUsers() {
        return authMapper.findAllUsers();
    }

    // 根据 groupId 获取用户
    public List<Auth> getUsersByGroupId(Long groupId) {
        return authMapper.findUsersByGroupId(groupId);
    }

    // 根据 roleId 获取用户
    public List<Auth> getUsersByRoleId(Long roleId) {
        return authMapper.findUsersByRoleId(roleId);
    }

    // 用户注册
    public String registerUser(Auth user) {
        try {
            validateUser(user, true);

            if (authMapper.isUsernameExists(user.getUsername())) {
                throw new IllegalArgumentException("用户名已存在");
            }
            if (authMapper.isPhoneNumberExists(user.getPhoneNumber())) {
                throw new IllegalArgumentException("手机号已存在");
            }

            // 根据组名称查找 group_id
            Integer groupId = groupMapper.findGroupIdByName(user.getGroupName());
            if (groupId == null) {
                throw new IllegalArgumentException("组名称不存在");
            }

            user.setCreatedAt(LocalDateTime.now());
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            user.setGroupId(groupId.longValue()); // 设置 group_id

            // 创建角色
            Role role = new Role();
            role.setRoleName(Role.RoleType.valueOf(user.getRoleName().toUpperCase()));
            role.setCreatedAt(LocalDateTime.now());

            roleService.createRole(role);

            // 获取最新插入的 role_id
            Long roleId = roleService.getLastInsertId();
            if (roleId == null) {
                throw new IllegalStateException("注册失败: 角色创建失败");
            }

            // 绑定 roleId 并插入用户
            user.setRoleId(roleId);
            authMapper.insertUser(user);

            // 返回 JWT 令牌
            return "注册成功，您的令牌是：" + jwtUtil.generateToken(user);
        } catch (NumberFormatException e) {
            return "注册失败: 角色ID格式错误";
        } catch (IllegalArgumentException e) {
            return "注册失败: " + e.getMessage();
        } catch (Exception e) {
            return "注册失败: 系统错误，请稍后再试";
        }
    }
    // 注销用户
    public String deleteUser(Long userId) {
        if (!authMapper.isUserIdExists(userId)) {
            return "用户不存在";
        }
        return authMapper.deleteUser(userId) > 0 ? "用户注销成功" : "用户注销失败";
    }

    // 更新用户信息
    public String updateUser(Auth user) {
        try {
            validateUser(user, false);
            if (authMapper.isPhoneNumberExistsForOtherUser(user.getPhoneNumber(), user.getUserId())) {
                throw new IllegalArgumentException("手机号已被其他用户占用");
            }
            Auth existingUser = authMapper.findByUsername(user.getUsername());
            if (existingUser != null && !passwordEncoder.matches(user.getPassword(), existingUser.getPassword())) {
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            }
            return authMapper.updateUser(user) > 0 ? "用户信息更新成功" : "用户信息更新失败";
        } catch (IllegalArgumentException e) {
            return "更新失败: " + e.getMessage();
        } catch (Exception e) {
            return "更新失败: 系统错误，请稍后再试";
        }
    }

    // 获取当前登录用户信息
    public Auth getCurrentUser(String token) {
        String username = jwtUtil.extractUsername(token);
        if (username == null) {
            throw new IllegalArgumentException("无效的 Token");
        }
        return authMapper.findByUsername(username);
    }


    // 用户信息校验
    private void validateUser(Auth user, boolean isNewUser) {
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (isNewUser && (user.getPassword() == null || user.getPassword().isEmpty())) {
            throw new IllegalArgumentException("密码不能为空");
        }
        if (user.getPhoneNumber() == null || user.getPhoneNumber().isEmpty()) {
            throw new IllegalArgumentException("手机号不能为空");
        }
        if (!isValidPhoneNumber(user.getPhoneNumber())) {
            throw new IllegalArgumentException("手机号格式不合法");
        }
        if (user.getEmail() != null && !user.getEmail().isEmpty() && !isValidEmail(user.getEmail())) {
            throw new IllegalArgumentException("邮箱格式不合法");
        }
    }

    // 手机号格式校验
    private boolean isValidPhoneNumber(String phoneNumber) {
        return Pattern.matches("^[0-9]{11}$", phoneNumber);
    }

    // 邮箱格式校验
    private boolean isValidEmail(String email) {
        return Pattern.matches("^[A-Za-z0-9+_.-]+@(.+)$", email);
    }
}
